#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <cstring>
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << " filemame" << std::endl;
        return 1;
    }
    std::string filename = argv[1];
    // 注意: 要成功进⾏写⼊映射，这⾥打开⽂件的模式必须是: O_RDWR
    int fd = ::open(filename.c_str(), O_RDONLY);
    if (fd < 0)
    {
        std::cerr << "open error" << std::endl;
        return 2;
    }
    // 获取⽂件真实⼤⼩
    struct stat st;
    ::fstat(fd, &st);
    char *mmap_addr = (char *)::mmap(nullptr, st.st_size, PROT_READ,
                                     MAP_SHARED, fd, 0);
    if (mmap_addr == MAP_FAILED)
    {
        perror("mmap");
        return 3;
    }
    std::cout << mmap_addr << std::endl;
    // 取消映射
    ::munmap(mmap_addr, st.st_size);
    // 关闭⽂件
    ::close(fd);
    return 0;
}